package su.samcom.calc.service;

import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import su.samcom.calc.exception.RouteNotFoundException;
import su.samcom.calc.model.dao.LocationDao;
import su.samcom.calc.model.entity.*;
import su.samcom.calc.service.record.Converter;
import su.samcom.calc.service.record.LocationRecord;
import su.samcom.calc.model.dao.PricePointDao;
import su.samcom.calc.model.dao.RouteDao;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Владислав
 * Date: 24.11.13
 * Time: 15:11
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional
public class CalculatorServiceImpl implements CalculatorService {

    public enum CargoType{
        SEPARATE,
        GENERAL;
    }

    @Autowired
    RouteDao routeDao;
    @Autowired
    PricePointDao priceDao;
    @Autowired
    LocationDao locationDao;

    @Override
    public List<Price> getCargoPrices(Long locationAId, Long locationBId, CargoType cargoType) throws RouteNotFoundException {
        Route route = routeDao.getRoute(locationAId, locationBId);

        if (route == null){
            throw new RouteNotFoundException();
        }

        PriceStrategy priceStrategy = null;
        if (route.getInheritedPriceStrategy() != null){
            priceStrategy = route.getInheritedPriceStrategy();
        } else {
            priceStrategy = route.getPriceStrategy();
        }
        PriceGroup priceGroup = null;
        if (cargoType == CargoType.GENERAL){
            priceGroup = priceStrategy.getGeneralCargo();
        } else if (cargoType == CargoType.SEPARATE){
            priceGroup = priceStrategy.getSeparateCargo();
        }
        List<Price> prices = priceDao.getByPriceGroupId(priceGroup.getId());

        return prices;
    }

    @Override
    public List<LocationRecord> getLocationRecords(String likeName) {
        List<Location> locations = locationDao.getLikeLocations(likeName);
        List<LocationRecord> locationFormRecords = new ArrayList<LocationRecord>();
        for(Location location : locations){
            LocationRecord locationFormRecord = new LocationRecord();
            Converter.populate(locationFormRecord, location);
            locationFormRecords.add(locationFormRecord);
        }
        return locationFormRecords;
    }
}
